from django.http import JsonResponse
from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def my_plan(params):
    '''
    我的计划
    '''
    dict = {
        "user_id": "user_id"
    }
    null_params = {
        "status_id": "status_id",
        "cycle_id": "cycle_id",
        "type_id": "type_id",
        "dept_id": "dept_id",
        "query_str": "query_str",
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    sql_plan_list = add_filter(PlanSqlMap.MY_PLAN, params, ["status_id", "cycle_id", "type_id", "dept_id", "query_str"], **PlanSqlMap.FILTER_PARAMS)
    my_plan_list = mysql_tools.select_all(sql_plan_list.format(**params))
    if not my_plan_list:
        return success_response([])
    if params.get("isall") != 1:
        my_plan_list = paging_simple(my_plan_list, params.get("page"), params.get("size"))
    for plan in my_plan_list:
        if plan.get("create_time"):
            plan["create_time"] = str(plan.get("create_time"))
    return success_response(my_plan_list)


def parent_plan(params):
    '''
    根据计划周期显示所有父级计划列表
    '''
    dict = {
        "cycle_id": "cycle_id"
    }
    pull_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, pull_params)
    sort_value = mysql_tools.select_one(PlanSqlMap.GET_SORT_VALUE.format(**params))
    sort = int(sort_value.get("sort_value"))
    while sort>0:   # sort_value为0时为最大级别
        sort -= 1
        params["sort"] = sort
        parent_type = mysql_tools.select_one(PlanSqlMap.GET_PARENT_TYPE.format(**params))
        if parent_type:
            parent_type_id = parent_type.get("cycle_id")
            break
        else:
            continue
    else:
        return success_response([])

    # 拿到上级plan列表
    result = mysql_tools.select_all(PlanSqlMap.GET_PLAN_BY_CYCLE.format(**{"cycle_id": parent_type_id}))
    if result:
        if params.get("isall") != 1:
            result = paging_simple(result, params.get("page"), params.get("size"))
    return success_response(result)


def add_plan(params):
    '''
    添加计划
    '''
    dict = {
        "user_id": "user_id",
        "title": "title",
        "type_id": "type_id",
        "dept_id": "dept_id",
        "cycle_id": "cycle_id",
        "status_id": "status_id",
        "start_time": "start_time",
        "end_time": "end_time",
        "plan_user_id": "plan_user_id",
        "plan_content": "plan_content"
    }
    null_params = {
        "project_id": "project_id",
        "attachments": "attachments",
        "parent_id": "parent_id"
    }
    replace_null = {
        "project_id": "null",
        "parent_id": "null"
    }
    params = get_params(params, dict, null_params, **replace_null)
    if isinstance(params, JsonResponse):
        return params

    # 根据类型查询menu的值
    type_name = mysql_tools.select_one(PlanSqlMap.GET_TYPE_NAME.format(**params))
    if type_name.get("type_name") == "个人计划":
        params["menu"] = "my"
    elif type_name.get("type_name") == "部门计划":
        params["menu"] = "dept"
    elif type_name.get("type_name") == "公司计划":
        params["menu"] = "company"
    else:
        params["menu"] = "null"

    # 判断是否有附件id
    if params.get("attachments"):
        sql_plan_add = PlanSqlMap.INSERT_PLAN.format(**params)
    else:
        sql_plan_add = PlanSqlMap.INSERT_PLAN_NO_ATTACH.format(**params)
    mysql_tools.execute_sql(sql_plan_add)
    plan_id = mysql_tools.select_one(PlanSqlMap.GET_ID).get("id")
    return success_response({"plan_id": plan_id})

def edit_plan(params):
    '''
    计划编辑
    '''
    dict = {
        "user_id": "user_id",
        "plan_id": "plan_id",
        "title": "title",
        "type_id": "type_id",
        "dept_id": "dept_id",
        "cycle_id": "cycle_id",
        "status_id": "status_id",
        "start_time": "start_time",
        "end_time": "end_time",
        "plan_user_id": "plan_user_id",
        "plan_content": "plan_content",
        "project_id": "project_id",
        "attachments": "attachments",
        "parent_id": "parent_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params

    # 拼接SQL语句
    sql_edit = PlanSqlMap.EDIT_PLAN
    for key, val in params.items():
        if key in ["user_id", "plan_id"]:
            continue
        elif key in ["attachments", "plan_content", "start_time", "end_time", "title"]:
            sql_edit += "%s='{%s}'," % (key, key)
        else:
            sql_edit += "%s={%s}," % (key, key)
    sql_edit = sql_edit[0:-1]
    sql_edit += " where plan_id={plan_id}"
    result = mysql_tools.execute_sql(sql_edit.format(**params), commit=True)
    if isinstance(result, JsonResponse):
        return result
    return success_response()


def del_plan(params):
    dict = {
        "user_id": "user_id",
        "plan_id": "plan_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params

    result = mysql_tools.execute_sql(PlanSqlMap.DEL_PLAN.format(**params), commit=True)
    if isinstance(result, JsonResponse):
        return result
    return success_response()




def check_plan(params):
    '''
    查看计划
    '''
    dict = {
        "user_id": "user_id",
        "plan_id": "plan_id"
    }
    null_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    print(PlanSqlMap.CHECK_PLAN.format(**params), "sql语句吧")
    result = mysql_tools.select_one(PlanSqlMap.CHECK_PLAN.format(**params))
    params["cycle_id"] = result.get("cycle_id")
    result["start_time"] = str(result.get("start_time"))
    result["end_time"] = str(result.get("end_time"))
    result["create_time"] = str(result.get("create_time"))
    result["attach_list"] = []
    if result.get("attachments"):
        attach_list = result.get("attachments").split(";")
        for attach in attach_list:
            if attach:
                attach_res = mysql_tools.select_one(PlanSqlMap.GET_ATTACH.format(**{"attach_id": int(attach)}))
                result["attach_list"].append(attach_res)
    result.pop("attachments")
    # 查询下级计划
    all_type = mysql_tools.select_all(PlanSqlMap.GET_PLAN_TYPE)
    type_list = []
    for type in all_type:
        type_list.append(type.get("sort_value"))
    sort_value = mysql_tools.select_one(PlanSqlMap.GET_SORT_VALUE.format(**params))
    sort = int(sort_value.get("sort_value"))
    while sort>=0:   # sort_value为0时为最大级别
        sort += 1
        params["sort"] = sort
        parent_type = mysql_tools.select_one(PlanSqlMap.GET_PARENT_TYPE.format(**params))
        # 判断下一级是否有数据
        if parent_type:
            parent_type_id = parent_type.get("cycle_id")
        # 写死,value大于5的视为没有
        elif sort <= 5:
            continue
        else:
            down_list = []
            break
        # 拿到下级plan列表
        down_list = mysql_tools.select_all(PlanSqlMap.GET_DOWN_PLAN_LIST.format(**{"cycle_id": parent_type_id}))
        if down_list:
            if params.get("isall") != 1:
                down_list = paging_simple(down_list, params.get("page"), params.get("size"))
        else:
            down_list = []
        break
    else:
        down_list = []

    result["down_plan"] = down_list
    return success_response(result)


def subordinates_plan(params):
    '''
    下属计划列表
    '''
    dict = {
        "user_id": "user_id"
    }
    null_params = {
        "status_id": "status_id",
        "cycle_id": "cycle_id",
        "type_id": "type_id",
        "dept_id": "dept_id",
        "query_str": "query_str",
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    # 查询我的下级
    sql = PlanSqlMap.FIND_ROLE_BY_ID.format(**params)
    role_id = mysql_tools.select_one(sql).get("role_value")
    if isinstance(role_id, JsonResponse):
        return role_id
    # if role_id <= 1:
    #     sql_subordinates_id = PlanSqlMap.subordinates_id_list_all.format(**params)
    # else:
    #     sql_subordinates_id = PlanSqlMap.subordinates_id_list.format(**params)
    sql_subordinates_id = PlanSqlMap.subordinates_id_list.format(**params)
    subordinates_id_all = mysql_tools.select_all(sql_subordinates_id)
    if isinstance(subordinates_id_all, JsonResponse):
        return subordinates_id_all
    if not subordinates_id_all:
        return success_response([])
    # 查询每个下级用户的计划
    result = []
    for sub in subordinates_id_all:
        params["user_id"] = sub.get("user_id")
        sql_plan_list = add_filter(PlanSqlMap.MY_PLAN, params, ["status_id", "cycle_id", "type_id", "dept_id", "query_str"],
                                   **PlanSqlMap.FILTER_PARAMS)
        user_result = mysql_tools.select_all(sql_plan_list.format(**params))
        if not user_result:
            continue
        for plan in user_result:
            if plan.get("create_time"):
                plan["create_time"] = str(plan.get("create_time"))
        result.extend(user_result)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    return success_response(result)


def dept_plan(params):
    '''
    部门计划
    :param params:
    :return:
    '''
    dict = {
        "user_id": "user_id"
    }
    null_params = {
        "status_id": "status_id",
        "cycle_id": "cycle_id",
        "dept_id": "dept_id",
        "query_str": "query_str",
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    type_id = mysql_tools.select_one(PlanSqlMap.GET_TYPE_ID.format(**{"type_name": "部门计划"}))
    params["type_id"] = type_id.get("type_id")
    sql_list = add_filter(PlanSqlMap.GET_PLAN_BY_TYPE, params, ["status_id", "cycle_id", "dept_id", "query_str"], **PlanSqlMap.FILTER_PARAMS)
    dept_plan_list = mysql_tools.select_all(sql_list.format(**params))
    if params.get("isall") != 1:
        dept_plan_list = paging_simple(dept_plan_list, params.get("page"), params.get("size"))
    return success_response(dept_plan_list)

def company_plan(params):
    '''
    公司计划
    :param params:
    :return:
    '''
    dict = {
        "user_id": "user_id"
    }
    null_params = {
        "status_id": "status_id",
        "cycle_id": "cycle_id",
        "dept_id": "dept_id",
        "query_str": "query_str",
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    type_id = mysql_tools.select_one(PlanSqlMap.GET_TYPE_ID.format(**{"type_name": "公司计划"}))
    params["type_id"] = type_id.get("type_id")
    sql_list = add_filter(PlanSqlMap.GET_PLAN_BY_TYPE, params, ["status_id", "cycle_id", "dept_id", "query_str"], **PlanSqlMap.FILTER_PARAMS)
    dept_plan_list = mysql_tools.select_all(sql_list.format(**params))
    if params.get("isall") != 1:
        dept_plan_list = paging_simple(dept_plan_list, params.get("page"), params.get("size"))
    return success_response(dept_plan_list)

def all_plan(params):
    '''
    全部计划
    '''
    dict = {
        "user_id": "user_id"
    }
    null_params = {
        "status_id": "status_id",
        "cycle_id": "cycle_id",
        "dept_id": "dept_id",
        "query_str": "query_str",
        "isall": "isAll",
        "size": "limit",
        "page": "page"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    sql_plan_list = add_filter(PlanSqlMap.ALL_PLAN, params, ["status_id", "cycle_id", "dept_id", "query_str"], **PlanSqlMap.FILTER_PARAMS)
    all_plan_list = mysql_tools.select_all(sql_plan_list.format(**params))
    if not all_plan_list:
        return success_response([])
    if isinstance(all_plan_list, JsonResponse):
        return all_plan_list
    if params.get("isall") != 1:
        all_plan_list = paging_simple(all_plan_list, params.get("page"), params.get("size"))
    for plan in all_plan_list:
        plan["create_time"] = str(plan.get("create_time"))
    return success_response(all_plan_list)


@format_response
def index(request):
    return com_views(request, {
        "all_plan": all_plan,
        "my_plan": my_plan,
        "parent_plan": parent_plan,
        "add_plan": add_plan,
        "edit_plan": edit_plan,
        "del_plan": del_plan,
        "check_plan": check_plan,
        "subordinates_plan": subordinates_plan,
        "dept_plan": dept_plan,
        "company_plan": company_plan
    })
